/**
 * @file select
 * @author liaoxuezhi@baidu.com
 *
 * https://github.com/JedWatson/react-select
 */
/* eslint fecs-indent: [0, "space", 2, 2] */

import * as React from 'react';
import {
  PureComponent,
  PropTypes
} from 'react';
import {findDOMNode} from 'react-dom';
import {Renderer} from '../../renderer';
import * as assign from 'object-assign';
import * as cx from 'classnames';
import ReactRangePicker from '../../../widgets/date-range/date-range';
import {Enhance as FormItem} from '../form-item';

@FormItem({
  type: 'date-range',
  validateSchema: 'http://amis.baidu.com/schemas/form.json#/definitions/dateRangeFormItem'
})
export default class DateRange extends PureComponent {
  static propTypes = {
    className: PropTypes.string,
    formMode: PropTypes.string,
    formHorizontal: PropTypes.object,
    joinValues: PropTypes.bool.isRequired,
    delimiter: PropTypes.string.isRequired
  };

  static defaultProps = {
    placeholder: '请选择日期范围',
    format: 'X',
    inputFormat: 'LL',
    joinValues: true,
    delimiter: ','
  };

  componentWillMount() {
    this.changeValue = this.changeValue.bind(this);
  }

  changeValue(newValue) {
    const {joinValues, delimiter} = this.props;
    
    if (joinValues) {
      newValue = [newValue.startDate, newValue.endDate].join(delimiter);
    }
    
    this.props.setValue(newValue);
  }

  render() {
    const {
      format,
      placeholder,
      inputFormat,

      joinValues,
      delimiter
    } = this.props;

    let value = this.props.getValue();

    if (joinValues && value) {
      const parts = String(value).split(delimiter);
      value = {
        startDate: parts[0],
        endDate: parts[1]
      };
    }


    return (
      <ReactRangePicker
        key="input"
        format={format}
        inputFormat={inputFormat}
        value={value}
        placeholder={placeholder}
        onChange={this.changeValue}
      />
    );
  }
}
